#include "pch.h"
#include "Cluster.h"


constexpr unsigned int INIT_TIMES = 5;
std::vector<Cluster::Vec> Cluster::initCenter(const std::vector<Vec>& points,uint cluster)
{
	float min_diff = FLT_MAX;
	uint min_index = -1;;
	std::vector<std::vector<Vec>> temp_center(INIT_TIMES);
	std::vector<uint> temp_index;
	klh_utility::Random<uint> rand(0, points.size());
	for (uint i = 0; i < INIT_TIMES; i++)
	{
		for (uint j = 0; j < cluster; j++)
		{
			temp_center[i].push_back(points[rand.getVal()]);
		}
		float diff;
		calDis(temp_center[i], points, temp_index, diff,cluster);
		if (diff < min_diff)
		{
			min_diff = diff;
			min_index = i;
		}
	}
	return temp_center[min_index];
}

bool Cluster::calDis(const std::vector<Vec> center, const std::vector<Vec>& points, std::vector<uint>& indexs, float& diff, uint cluster)
{
	if (center.size() != cluster)
		return false;
	diff = 0;
	indexs.clear(); indexs.reserve(points.size());
	for (const auto p : points)
	{
		float min_dis = FLT_MAX;
		uint min_index = -1;
		for (uint i = 0; i < cluster; i++)
		{
			const auto dis = klh_utility::Point<float>::p2PDis(p, center[i]);
			if (dis < min_dis)
			{
				min_dis = dis;
				min_index = i;
			}
		}
		indexs.push_back(min_index);
		diff += min_dis;
	}
	diff /= points.size();
	return true;
}

